package com.jms.activemq.topic;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnectionFactory;

/**
 * 消费者
 * 主题模式
 * 
 */
public class AppCustomer {
	private static final String url = "tcp://127.0.0.1:61616";
    private static final String queueName = "topic-test";

	public static void main(String[] args) throws JMSException {
		//1.创建连接工厂
		ConnectionFactory connectionFactory=new ActiveMQConnectionFactory(url);
		//2.创建连接
		Connection connection=connectionFactory.createConnection();
		//3.启动连接
		connection.start();
		//4.创建会话
		Session session=connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
		//5.创建一个目标
		/*主题模式此处创建的是topic*/
		Destination destination=session.createTopic(queueName);
		//6.创建一个消费者
		MessageConsumer messageConsumer=session.createConsumer(destination);
		//7.创建一个监听器
		messageConsumer.setMessageListener(new MessageListener() {
			public void onMessage(Message message) {
				TextMessage textMessage=(TextMessage)message;
				try {
					//8.接收消息
					System.out.println("接收消息："+textMessage.getText());
				} catch (JMSException e) {
					e.printStackTrace();
				}
			}
		});
		/*消费者连接不允许被关闭，消息的接收是异步的，关闭连接会导致消息不能被消费*/
		//session.close(); 
	}
}
